// components/reminder-setting/reminder-setting.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 是否默认处于编辑模式
    defaultEditing: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    reminderEnabled: true,
    reminderTime: '08:00',
    medicationName: '降压药',
    isEditing: false,
    tempReminderTime: '',
    tempMedicationName: '',
    tempReminderEnabled: true
  },

  /**
   * 组件生命周期函数，在组件实例进入页面节点树时执行
   */
  attached() {
    // 从本地存储加载设置
    this.loadSettings();
    
    // 设置初始编辑状态
    this.setData({
      isEditing: this.properties.defaultEditing,
      tempReminderTime: this.data.reminderTime,
      tempMedicationName: this.data.medicationName,
      tempReminderEnabled: this.data.reminderEnabled
    });
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 从本地存储加载设置
    loadSettings() {
      const settings = wx.getStorageSync('settings') || {};
      
      this.setData({
        reminderEnabled: settings.reminderEnabled !== undefined ? settings.reminderEnabled : true,
        reminderTime: settings.reminderTime || '08:00',
        medicationName: settings.medicationName || '降压药'
      });
    },

    // 切换编辑模式
    onEdit() {
      this.setData({
        isEditing: true,
        tempReminderTime: this.data.reminderTime,
        tempMedicationName: this.data.medicationName,
        tempReminderEnabled: this.data.reminderEnabled
      });
    },

    // 取消编辑
    onCancel() {
      this.setData({
        isEditing: false
      });
    },

    // 保存设置
    onSave() {
      const newSettings = {
        reminderEnabled: this.data.tempReminderEnabled,
        reminderTime: this.data.tempReminderTime,
        medicationName: this.data.tempMedicationName || '降压药'
      };

      // 保存到本地存储
      wx.setStorageSync('settings', {
        ...wx.getStorageSync('settings'),
        ...newSettings
      });

      // 更新组件数据
      this.setData({
        reminderEnabled: newSettings.reminderEnabled,
        reminderTime: newSettings.reminderTime,
        medicationName: newSettings.medicationName,
        isEditing: false
      });

      // 触发事件通知父组件
      this.triggerEvent('settingsSaved', newSettings);

      // 显示保存成功提示
      wx.showToast({
        title: '设置已保存',
        icon: 'success',
        duration: 1500
      });
    },

    // 提醒开关变化
    onReminderSwitchChange(e) {
      this.setData({
        tempReminderEnabled: e.detail.value
      });
    },

    // 时间选择变化
    onTimeChange(e) {
      this.setData({
        tempReminderTime: e.detail.value
      });
    },

    // 药品名称输入变化
    onMedicationNameInput(e) {
      this.setData({
        tempMedicationName: e.detail.value
      });
    }
  }
})